package com.ruoyi.web.controller.system;

import java.lang.reflect.Field;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DtQuestion;
import com.ruoyi.system.service.IDtQuestionService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 党统督办Controller
 * 
 * @author ruoyi
 * @date 2024-03-18
 */
@RestController
@RequestMapping("/system/question")
public class DtQuestionController extends BaseController
{
    @Autowired
    private IDtQuestionService dtQuestionService;
    
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    
    /**
     * 查询党统督办列表
     */
    @PreAuthorize("@ss.hasPermi('system:question:list')")
    @GetMapping("/list")
    public TableDataInfo list(DtQuestion dtQuestion)
    {
        startPage();
        List<DtQuestion> list = dtQuestionService.selectDtQuestionList(dtQuestion);
        return getDataTable(list);
    }
    
    /**
     * 查询党统督办列表(发布环节)
     */
    @PreAuthorize("@ss.hasPermi('system:question:list')")
    @GetMapping("/listForPublish")
    public TableDataInfo listForPublish(DtQuestion dtQuestion)
    {
        startPage();
        List<DtQuestion> list = dtQuestionService.selectDtQuestionListForPublish(dtQuestion);
        return getDataTable(list);
    }
    
    /**
     * 查询党统督办列表(整改环节)
     */
    @GetMapping("/listForReform")
    public TableDataInfo listForReform(DtQuestion dtQuestion)
    {
        startPage();
        List<DtQuestion> list = dtQuestionService.selectDtQuestionListForReform(dtQuestion);
        return getDataTable(list);
    }
    
    /**
     * 查询党统督办列表(审核环节)
     */
    @PreAuthorize("@ss.hasPermi('system:question:list')")
    @GetMapping("/listForCheck")
    public TableDataInfo listForCheck(DtQuestion dtQuestion)
    {
        startPage();
        List<DtQuestion> list = dtQuestionService.selectDtQuestionListForCheck(dtQuestion);
        return getDataTable(list);
    }

    /**
     * 导出党统督办列表
     */
    @PreAuthorize("@ss.hasPermi('system:question:export')")
    @Log(title = "党统督办", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DtQuestion dtQuestion)
    {
        List<DtQuestion> list = dtQuestionService.selectDtQuestionList(dtQuestion);
        ExcelUtil<DtQuestion> util = new ExcelUtil<DtQuestion>(DtQuestion.class);
        util.exportExcel(response, list, "党统督办数据");
    }

    /**
     * 获取党统督办详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(dtQuestionService.selectDtQuestionById(id));
    }

    /**
     * 新增党统督办
     */
    @PreAuthorize("@ss.hasPermi('system:question:add')")
    @Log(title = "党统督办", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DtQuestion dtQuestion)
    {
        return toAjax(dtQuestionService.insertDtQuestion(dtQuestion));
    }

    /**
     * 修改党统督办
     */
//    @PreAuthorize("@ss.hasPermi('system:question:edit')")
    @Log(title = "党统督办", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DtQuestion dtQuestion)
    {
    	String userName = SecurityUtils.getLoginUser().getUser().getNickName();
    	Long userID = SecurityUtils.getUserId();
    	
        return toAjax(dtQuestionService.updateDtQuestion(dtQuestion));
    }

    /**
     * 删除党统督办
     */
    @PreAuthorize("@ss.hasPermi('system:question:remove')")
    @Log(title = "党统督办", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(dtQuestionService.deleteDtQuestionByIds(ids));
    }
    
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        //List<DtQuestion> questionList = new ArrayList<>();
    	int successCount = 0;
    	int failCount = 0;
    	int i = 0 ;
        try(Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            //Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0); // 假设Excel中只有一个Sheet
         // 获取DtQuestion类的Class对象
            Class<DtQuestion> clazz = DtQuestion.class;

            // 从第二行开始遍历Excel文件，跳过表头
            for (i = 1; i <= sheet.getLastRowNum(); i++) {
            	
            	int result;
                Row row = sheet.getRow(i);
                DtQuestion data = clazz.newInstance();

                // 根据列数给实体类赋值
                Cell cell1 = row.getCell(0);
                data.setIssue(cellValue(cell1));

                Cell cell2 = row.getCell(1);
                data.setEdit(cellValue(cell2));

                Cell cell3 = row.getCell(2);
                System.out.println("截止日期格式转化：" + formatDateValue(cell3));
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                LocalDate deadline = LocalDate.parse(formatDateValue(cell3), formatter);
                data.setDeadline(deadline);

                Cell cell4 = row.getCell(3);
                data.setDeptId(cellValue(cell4));
                
                String id = generateRandomString(18);
                data.setId(id);
                
                String status = "1";
                data.setStatus(status);
                
                result = dtQuestionService.insertDtQuestion(data);
                
                if(result == 1 ) {
                	successCount += 1;
                }else if (result == 0) {
                	failCount += 1;
                }else {}
            }
            
        } catch (Exception e) {
            // 处理异常
        	e.printStackTrace();
        }
        return success("共导入了" + (i-1) + "条数据，其中" + successCount + "条成功，" + ((i-1)-successCount) + "条失败");
    }
    
    private String cellValue(Cell cell) {
        String cellValue = null;
        System.out.println("cell内容为：" + cell);
        System.out.println(cell.getCellType());
        if (cell.getCellType() == CellType.STRING) {
            cellValue = cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
            } else {
                cellValue = String.valueOf(cell.getNumericCellValue());
            }
        } else {
            // 其他情况的处理
        }
        return cellValue;
    }
    
    //将截止日期单元格转为日期格式的字符串
    private String formatDateValue(Cell cell) {
        if (DateUtil.isCellDateFormatted(cell)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 定义目标日期格式
            return dateFormat.format(cell.getDateCellValue()); // 格式化日期值为指定格式的字符串
        } else {
            double numericValue = cell.getNumericCellValue();
            DecimalFormat decimalFormat = new DecimalFormat("#"); // 定义数字格式
            return decimalFormat.format(numericValue); // 将数字转换为字符串
        }
    }
    
    public static String generateRandomString(int length) {
        SecureRandom random = new SecureRandom();
        StringBuilder result = new StringBuilder();
        int charactersLength = CHARACTERS.length();
        for (int i = 0; i < length; i++) {
            result.append(CHARACTERS.charAt(random.nextInt(charactersLength)));
        }
        return result.toString();
    }
}
